<template>
  <div class="file-converter">
    <div class="card">
      <div class="card-header">
        <h2>文件转换工具</h2>
      </div>
      
      <div class="upload-section">
        <div class="file-upload"
             @drop.prevent="handleDrop"
             @dragover.prevent="handleDragOver"
             @dragleave.prevent="handleDragLeave">
          <input 
            type="file" 
            id="file" 
            @change="handleFileChange"
            class="file-input"
          >
          <label for="file" class="upload-button" ref="uploadLabel">选择文件</label>
          <div class="drag-tip">或将文件拖到此处</div>
          <div class="file-name" v-if="selectedFile">
            已选择: {{ selectedFile.name }}
          </div>
        </div>
      </div>

      <div class="download-section" v-if="selectedFile">
        <button 
          class="download-btn" 
          @click="handleConvert"
          :disabled="isConverting"
        >
          {{ isConverting ? '转换中...' : '开始转换' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import JSONbig from 'json-bigint'

const selectedFile = ref<File | null>(null)
const isConverting = ref(false)

const handleFileChange = (event: Event) => {
  const input = event.target as HTMLInputElement
  const file = input.files?.[0]
  if (!file) return
  selectedFile.value = file
}

const handleConvert = async () => {
  if (!selectedFile.value) return
  isConverting.value = true
  
  try {
    // 读取文件内容
    const text = await selectedFile.value.text()
    
    // 将文件按行分割
    const lines = text.split('\n').filter(line => line.trim())
    
    // 解析每一行，确保是有效的JSON对象
    const objects = lines.map(line => {
      try {
        // 预处理行数据，将大数字转换为字符串格式
        // const processedLine = line.replace(/"([^"]+)":\s*(\d{15,})/g, '"$1":"$2"')
        
        // 解析处理后的JSON
        return JSONbig.parse(line)
      } catch (e) {
        throw new Error(`无效的JSON格式: ${line}`)
      }
    })
    
    // 创建最终的JSON数组，使用 replacer 函数保持大数字的字符串格式
    const jsonArray = JSON.stringify(objects, (key, value) => {
      // 如果是数字字符串且长度超过15位，确保它在输出时仍然是字符串
      if (typeof value === 'string' && /^\d{15,}$/.test(value)) {
        return value
      }
      return value
    }, 2)
    
    // 创建并下载文件
    const blob = new Blob([jsonArray], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = selectedFile.value.name.replace(/\.[^/.]+$/, '') + '_converted.json'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)

    // 重置状态
    selectedFile.value = null
    const input = document.getElementById('file') as HTMLInputElement
    if (input) {
      input.value = ''
    }

    ElMessage.success('转换成功')
  } catch (error) {
    console.error('转换失败:', error)
    ElMessage.error(error instanceof Error ? error.message : '转换失败，请重试')
  } finally {
    isConverting.value = false
  }
}

// 处理拖拽进入
const handleDragOver = (event: DragEvent) => {
  event.target && (event.target as HTMLElement).closest('.file-upload')?.classList.add('dragover')
}

// 处理拖拽离开
const handleDragLeave = (event: DragEvent) => {
  event.target && (event.target as HTMLElement).closest('.file-upload')?.classList.remove('dragover')
}

// 处理文件拖放
const handleDrop = (event: DragEvent) => {
  event.target && (event.target as HTMLElement).closest('.file-upload')?.classList.remove('dragover')
  const file = event.dataTransfer?.files[0]
  
  if (!file) return
  
  // 创建一个新的 FileList 对象
  const dataTransfer = new DataTransfer()
  dataTransfer.items.add(file)
  
  // 更新 input 的文件
  const fileInput = document.getElementById('file') as HTMLInputElement
  if (fileInput) {
    fileInput.files = dataTransfer.files
    handleFileChange({ target: { files: [file] } } as unknown as Event)
  }
}
</script>

<style scoped>
.file-converter {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.06);
  padding: 24px;
}

.card-header {
  margin-bottom: 24px;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  color: #2d3748;
  font-weight: 600;
}

.upload-section {
  width: 100%;
  margin: 20px 0;
}

.file-upload {
  position: relative;
  display: block;
  padding: 30px;
  border: 2px dashed #e2e8f0;
  border-radius: 8px;
  background: #f8fafc;
  transition: all 0.3s ease;
  text-align: center;
  width: 100%;
  margin: 0 auto;
}

.file-upload.dragover {
  border-color: #4f46e5;
  background: #eef2ff;
}

.file-input {
  position: absolute;
  width: 0;
  height: 0;
  opacity: 0;
}

.upload-button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 15px 30px;
  background: #4f46e5;
  color: white;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
  width: 80%;
  max-width: 400px;
  font-size: 16px;
}

.upload-button:hover {
  background: #4338ca;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
}

.drag-tip {
  margin-top: 10px;
  color: #64748b;
  font-size: 14px;
}

.file-name {
  margin-top: 15px;
  color: #4f46e5;
  font-size: 14px;
  font-weight: 500;
}

.download-section {
  margin-top: 24px;
  text-align: center;
}

.download-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 15px 30px;
  background: #4f46e5;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 16px;
  font-weight: 500;
  width: 80%;
  max-width: 400px;
}

.download-btn:hover:not(:disabled) {
  background: #4338ca;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
}

.download-btn:disabled {
  background: #94a3b8;
  cursor: not-allowed;
}
</style> 